from marshmallow_sqlalchemy import ModelSchema
from marshmallow import fields
from application.users.models import *
from application import db


# 定义Users model到marshmallow的映射
# model -> json   json -> model
class UsersSchema(ModelSchema):
    class Meta(ModelSchema.Meta):
        model = Users
        sqla_session = db.session

    # id是自动生成的，不需要客户端传给我们，所以只需要从Model序列化成json
    # dump_only=True读取操作，不是写入操作
    id = fields.Integer(dump_only=True)
    name = fields.String(attribute='name', required=True, validate=lambda s: len(s.strip()) > 0,
                             error_messages={'required': '用户名必填', 'validator_failed': '用户名不能为空'})
    mobile = fields.String(required=True, validate=lambda s: len(s.strip()) == 11,
                           error_messages={'required': '手机号必填', 'validator_failed': '手机号长度不正确'})
    # 只允许从json序列化成model
    password = fields.String(load_only=True)
    user_type = fields.Integer(required=True)
